package com.lanyou.cook.camel.service.impl;

import java.io.IOException;
import java.net.SocketException;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;

import com.lanyou.cook.camel.commons.Constants;
import com.lanyou.cook.camel.dao.impl.AccessLogDao;
import com.lanyou.cook.camel.dao.impl.FtpServerDao;
import com.lanyou.cook.camel.datadictionary.IfEnableType;
import com.lanyou.cook.camel.datadictionary.TransportResultType;
import com.lanyou.cook.camel.entity.AccessLog;
import com.lanyou.cook.camel.entity.Ftp;
import com.lanyou.cook.camel.entity.FtpServer;
import com.lanyou.cook.camel.exception.AuthException;
import com.lanyou.cook.camel.service.FtpService;
import com.lanyou.cook.camel.service.LogService;
import com.lanyou.cook.camel.util.CamelFactory;
import com.lanyou.cook.camel.util.CommUtil;
import com.lanyou.cook.camel.util.FtpUtil;

public class LogServiceImpl implements LogService {
	private static Logger logger = Logger.getLogger(LogServiceImpl.class);
	private FtpService ftpService;

	private AccessLogDao accessLogDao;

	private FtpServerDao ftpServerDao;

	public LogServiceImpl() {
		super();
	}

	public LogServiceImpl(FtpService ftpService, AccessLogDao accessLogDao) {
		this.ftpService = ftpService;
		this.accessLogDao = accessLogDao;
	}

	@Override
	public void writeLog(String interfaceCode, String interfaceName,
			String sourceIps, String targetIps, String fileName, String fileSize)
			throws AuthException {
		// TODO 自动生成的方法存根
//		logger.info("[LogServiceImpl.writeLog]:interfaceCode=" + interfaceCode
//				+ "--interfaceName=" + interfaceName + "--sourceIps="
//				+ sourceIps + "--targetIps=" + targetIps + "--fileName="
//				+ fileName + "--fileSize" + fileSize);
		Ftp ftp = ftpService.getFtpByCode(interfaceCode, sourceIps, targetIps,
				fileName, fileSize);
		AccessLog accessLog = new AccessLog();
		accessLog.setId(UUID.randomUUID().toString());
		accessLog.setInterfaceId(ftp.getId());
		accessLog.setSourceIps(sourceIps);
		accessLog.setTargetIps(targetIps);
		accessLog.setFileName(fileName);
		accessLog.setFileSize(fileSize);
		accessLog.setTransportTime(new Date());
		accessLog.setIsEnable(IfEnableType.ENABLE.ValueCode);
		accessLog.setCreator("SYSTEM");
		accessLog.setModifier("SYSTEM");
		accessLog.setCreatedDate(new Date());
		accessLog.setLastUpdatedDate(new Date());
		accessLog.setTransportResult(TransportResultType.SUCCESS.ValueCode);
		accessLog.setTransportResutlDes(Constants.MSG_INTERFACE_SUCCESS);
		accessLog.setInterfaceName(interfaceName);
		accessLog.setFieldSystemId(ftp.getSystemId());
		accessLog.setExecuteTaskNode(CommUtil.EXECUTE_TASK_NODE);
		// System.out.println("hello");
		accessLogDao.save(accessLog);
//		logger.info("[LogServiceImpl.writeLog]:日志正常写入");
		// CamelFactory.routeMap.get(interfaceCode).get(sourceIps+targetIps);
	}

	@Override
	public void writeErrLog(String interfaceCode, String interfaceName,
			String sourceIp, String targetIp, String fileName, String fileSize)
			throws AuthException {
//		logger.info("[LogServiceImpl.writeErrLog]:interfaceCode=" + interfaceCode
//				+ "--interfaceName=" + interfaceName + "--sourceIp="
//				+ sourceIp + "--targetIp=" + targetIp + "--fileName="
//				+ fileName + "--fileSize" + fileSize);
		Ftp ftp = ftpService.getFtpByCode(interfaceCode, sourceIp, targetIp,
				fileName, fileSize);
		AccessLog accessLog = new AccessLog();
		accessLog.setId(UUID.randomUUID().toString());
		accessLog.setInterfaceId(ftp.getId());
		accessLog.setSourceIps(sourceIp);
		accessLog.setTargetIps(targetIp);
		accessLog.setFileName(fileName);
		accessLog.setFileSize(fileSize);
		accessLog.setTransportTime(new Date());
		accessLog.setIsEnable(IfEnableType.ENABLE.ValueCode);
		accessLog.setCreator("SYSTEM");
		accessLog.setModifier("SYSTEM");
		accessLog.setCreatedDate(new Date());
		accessLog.setLastUpdatedDate(new Date());
		accessLog.setTransportResult(TransportResultType.FAILD.ValueCode);
		accessLog.setTransportResutlDes(Constants.MSG_INTERFACE_FAIL);
		accessLog.setInterfaceName(interfaceName);
		accessLog.setFieldSystemId(ftp.getSystemId());
		accessLog.setExecuteTaskNode(CommUtil.EXECUTE_TASK_NODE);
		// System.out.println("hello");
		int i = accessLogDao.save(accessLog);
		logger.info("[LogServiceImpl.writeLog]:"+interfaceCode + "---" + sourceIp + "---" + i + "---"
				+ Constants.MSG_INTERFACE_FAIL);
		// notifyCamel(ftp);
	}

	@Override
	public void checkFTP(String interfaceCode, String interfaceName, String id)
			throws AuthException {
		FtpServer ftpser = ftpServerDao.findFtpServersById(id);
		try {
			FtpUtil.connectFtp(ftpser);
			FTPFile[] files = FtpUtil.getFtp().listFiles();
			if (files == null || files.length == 0) {
				System.out.println(ftpser.getHost() + ":" + ftpser.getPort()
						+ "--ftp服务器上没有文件");
				writeErrLog(interfaceCode, interfaceName, ftpser.getHost()
						+ ":" + ftpser.getPort(), "0.0.0.0:21",
						ftpser.getFileName(), "0");
			}
		} catch (SocketException e) {
			System.out.println("[checkFTP]SocketException 异常");
			writeErrLog(interfaceCode, interfaceName, ftpser.getHost() + ":"
					+ ftpser.getPort(), "0.0.0.0:21", ftpser.getFileName(), "0");
		} catch (IOException e) {
			System.out.println("[checkFTP]IOException 异常");
			writeErrLog(interfaceCode, interfaceName, ftpser.getHost() + ":"
					+ ftpser.getPort(), "0.0.0.0:21", ftpser.getFileName(), "0");
		} finally {
			FtpUtil.closeFtp();
		}
	}

	public void notifyCamel(Ftp ftp) {
		synchronized (CamelFactory.getCamel(ftp.getCode())) {
			CamelFactory.getCamel(ftp.getCode()).notify();
		}
	}

	public String arrToStr(String[] strs) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < strs.length; i++) {
			sb.append(strs[i] + ";");
		}
		String s = sb.toString();
		return s;
	}

	public FtpService getFtpService() {
		return ftpService;
	}

	public void setFtpService(FtpService ftpService) {
		this.ftpService = ftpService;
	}

	public AccessLogDao getAccessLogDao() {
		return accessLogDao;
	}

	public void setAccessLogDao(AccessLogDao accessLogDao) {
		this.accessLogDao = accessLogDao;
	}

	public FtpServerDao getFtpServerDao() {
		return ftpServerDao;
	}

	public void setFtpServerDao(FtpServerDao ftpServerDao) {
		this.ftpServerDao = ftpServerDao;
	}

}
